package com.xiaochong.bitong.api.controller;

import com.alibaba.fastjson.JSON;
import com.netflix.discovery.converters.Auto;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.bitong.api.component.RedisCacheComponent;
import com.xiaochong.bitong.api.config.hbase.HbaseBaseQueryComponent;
import com.xiaochong.bitong.api.constant.HttpHeaderCons;
import com.xiaochong.bitong.api.constant.ReturnCode;
import com.xiaochong.bitong.api.service.CommonService;
import com.xiaochong.bitong.api.service.CurrencyService;
import com.xiaochong.bitong.api.utils.ApiVersion;
import com.xiaochong.bitong.api.utils.ListSortUtil;
import com.xiaochong.bitong.api.utils.RequestUtil;
import com.xiaochong.bitong.api.utils.StringUtil;
import com.xiaochong.service.common.config.oss.OSSTool;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.common.data.hbasepo.TradesToKLine;
import com.xiaochong.tir.common.data.mapper.CurrencyInfoMapper;
import com.xiaochong.tir.common.data.mapper.ExchangeTransactionpairMiddleMapper;
import com.xiaochong.tir.common.data.mapper.SelfSelectedMapper;
import com.xiaochong.tir.common.data.po.ConceptCategory;
import com.xiaochong.tir.common.data.po.CurrencyInfo;
import com.xiaochong.tir.common.data.po.ExchangeTransactionpairMiddle;
import com.xiaochong.tir.common.data.po.SelfSelected;
import com.xiaochong.tir.common.data.redisPo.CoinPriceVo;
import com.xiaochong.tir.common.data.redisPo.KActionTotalPo;
import com.xiaochong.tir.common.data.vo.*;
import com.xiaochong.tir.common.data.vo.app.CurrencyStatistics;
import com.xiaochong.tir.common.exception.hbase.HbaseCloseExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseConnectionExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseGetTableExcetion;
import com.xiaochong.tir.common.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 币种
 * @author MengXiangDong
 */
@RestController
@Api(value = "币种")
@RequestMapping(value = ApiVersion.API_V1_PREFIX+"/currency")
public class CurrencyController {

	@Autowired
	private RedisServer redisServer;

	@Autowired
	private CurrencyService currencyService;

	@Autowired
	private ExchangeTransactionpairMiddleMapper exchangeTransactionpairMiddleMapper;

	@Autowired
	private RedisCacheComponent redisCacheComponent;

	@Autowired
	private CommonService commonService;

	@Autowired
	private SelfSelectedMapper selfSelectedMapper;

	@Auto
	private CurrencyInfoMapper currencyInfoMapper;

	/**
	 * 成交榜
	 */
	@ApiOperation(value = "成交榜" , notes = "成交榜")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageIndex", value = "页数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "条数", required = true, dataType = "Integer", paramType = "query")
	})
	@PostMapping("turnover")
	public ApiResultVo<List<CurrencyQuotationResultVo>> turnover(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,
																 @RequestParam(value = "pageSize", required = true) Integer pageSize
																 ){
		CurrencyQuotationVo currencyQuotationVo = new CurrencyQuotationVo();
		currencyQuotationVo.setField( "volume24h" );
		currencyQuotationVo.setType( "desc" );
		currencyQuotationVo.setPageIndex( pageIndex );
		currencyQuotationVo.setPageSize( pageSize );
		ApiResultVo apiResultVo=currencyService.getCurrencyQuotation( currencyQuotationVo );
		List<CurrencyQuotationResultVo> currencyQuotationResultVoList = (List<CurrencyQuotationResultVo>) apiResultVo.getData();
        //分页
		if(currencyQuotationVo.getPageIndex()==null){
			currencyQuotationVo.setPageIndex( 1 );
		}
		if(currencyQuotationVo.getPageSize()==null){
			currencyQuotationVo.setPageSize( 15 );
		}
		Object result= StringUtil.pageBean(currencyQuotationResultVoList,currencyQuotationVo.getPageIndex(),currencyQuotationVo.getPageSize()  );
		apiResultVo.setData( result );
		apiResultVo.setTotal( currencyQuotationResultVoList.size() );
		return apiResultVo;
	}

	/**
	 * 成交榜
	 */
	@ApiOperation(value = "涨幅榜" , notes = "涨幅榜")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageIndex", value = "页数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "条数", required = true, dataType = "Integer", paramType = "query")
	})
	@PostMapping("change24hdesc")
	public ApiResultVo<List<CurrencyQuotationResultVo>> change24h(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,
																 @RequestParam(value = "pageSize", required = true) Integer pageSize
	){
		CurrencyQuotationVo currencyQuotationVo = new CurrencyQuotationVo();
		currencyQuotationVo.setField( "change24h" );
		currencyQuotationVo.setType( "desc" );
		currencyQuotationVo.setPageIndex( pageIndex );
		currencyQuotationVo.setPageSize( pageSize );
		ApiResultVo apiResultVo=currencyService.getCurrencyQuotation( currencyQuotationVo );
		List<CurrencyQuotationResultVo> currencyQuotationResultVoList = (List<CurrencyQuotationResultVo>) apiResultVo.getData();
		Iterator<CurrencyQuotationResultVo> currencyQuotationResultVoListIterator = currencyQuotationResultVoList.iterator();
		while (currencyQuotationResultVoListIterator.hasNext()) {
			CurrencyQuotationResultVo currencyQuotationResultVo = currencyQuotationResultVoListIterator.next();
			if (currencyQuotationResultVo.getChange24h()<=0) {
				currencyQuotationResultVoListIterator.remove();
			}
		}
		//分页
		if(currencyQuotationVo.getPageIndex()==null){
			currencyQuotationVo.setPageIndex( 1 );
		}
		if(currencyQuotationVo.getPageSize()==null){
			currencyQuotationVo.setPageSize( 15 );
		}
		Object result= StringUtil.pageBean(currencyQuotationResultVoList,currencyQuotationVo.getPageIndex(),currencyQuotationVo.getPageSize()  );
		apiResultVo.setData( result );
		apiResultVo.setTotal( currencyQuotationResultVoList.size() );
		return apiResultVo;
	}


	/**
	 * 成交榜
	 */
	@ApiOperation(value = "跌幅榜" , notes = "跌幅榜")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageIndex", value = "页数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "条数", required = true, dataType = "Integer", paramType = "query")
	})
	@PostMapping("change24hasc")
	public ApiResultVo<List<CurrencyQuotationResultVo>> change24hasc(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,
																  @RequestParam(value = "pageSize", required = true) Integer pageSize
	){
		CurrencyQuotationVo currencyQuotationVo = new CurrencyQuotationVo();
		currencyQuotationVo.setField( "change24h" );
		currencyQuotationVo.setType( "asc" );
		currencyQuotationVo.setPageIndex( pageIndex );
		currencyQuotationVo.setPageSize( pageSize );
		ApiResultVo apiResultVo=currencyService.getCurrencyQuotation( currencyQuotationVo );
		List<CurrencyQuotationResultVo> currencyQuotationResultVoList = (List<CurrencyQuotationResultVo>) apiResultVo.getData();
		Iterator<CurrencyQuotationResultVo> currencyQuotationResultVoListIterator = currencyQuotationResultVoList.iterator();
		while (currencyQuotationResultVoListIterator.hasNext()) {
			CurrencyQuotationResultVo currencyQuotationResultVo = currencyQuotationResultVoListIterator.next();
			if (currencyQuotationResultVo.getChange24h()>=0) {
				currencyQuotationResultVoListIterator.remove();
			}
		}
		//分页
		if(currencyQuotationVo.getPageIndex()==null){
			currencyQuotationVo.setPageIndex( 1 );
		}
		if(currencyQuotationVo.getPageSize()==null){
			currencyQuotationVo.setPageSize( 15 );
		}
		Object result= StringUtil.pageBean(currencyQuotationResultVoList,currencyQuotationVo.getPageIndex(),currencyQuotationVo.getPageSize()  );
		apiResultVo.setData( result );
		apiResultVo.setTotal( currencyQuotationResultVoList.size() );
		return apiResultVo;
	}

	@ApiOperation(value = "首页TIR权重指数", notes = "首页TIR权重指数，x轴时间，y轴权重指数")
	@PostMapping("/weightIndex")
	public ApiResultVo<ApiWeightIndexVo> getWeightIndex(){
		return currencyService.getWeightIndex();
	}

	@ApiOperation(value = "首页TIR大盘指数", notes = "首页TIR大盘指数，x轴时间，y轴权重指数")
	@PostMapping("/marketIndex")
	public ApiResultVo<ApiMarketIndexVo> getGrailIndex(){
		return currencyService.getGrailIndex();
	}

	@ApiOperation(value = "行业分类-指数", notes = "行业分类-指数，x轴时间，y轴行业指数和涨幅")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageIndex", value = "页数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "条数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "field", value = "排序字段", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "排序方式（desc:降序，asc:升序）", required = true, dataType = "String", paramType = "query")
	})
	@PostMapping("/allIndustryIndex")
	public ApiResultVo<ApiIndustryIndexVo> getAllIndustryIndex(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,
															   @RequestParam(value = "pageSize", required = true) Integer pageSize,
															   @RequestParam(value = "field", required = true) String field,
															   @RequestParam(value = "type", required = true) String type){
		ApiResultVo apiResultVo = new ApiResultVo();

		try{
			List<ApiIndustryTabInfoVo> apiIndustryTabInfoVoList = currencyService.getIndustryTabInfo();
			List<ApiIndustryIndexVo> resultList = new ArrayList<>(  );
			for (int i=0;i<apiIndustryTabInfoVoList.size();i++){
				ApiIndustryTabInfoVo apiIndustryTabInfoVo = apiIndustryTabInfoVoList.get( i );
				apiResultVo = currencyService.getAllIndustryIndex(apiIndustryTabInfoVo.getIndustryId(),apiIndustryTabInfoVo.getIndustry());
				ApiIndustryIndexVo apiIndustryIndexVo = (ApiIndustryIndexVo) apiResultVo.getData();
				resultList.add( apiIndustryIndexVo );
			}
			//排序
			ListSortUtil util=new ListSortUtil();
			util.mySort( resultList, field, type );

			//分页
			if(pageIndex==0){
				pageIndex=1;
			}
			if(pageSize==0){
				pageSize=6;
			}
			Object result= StringUtil.pageBean(resultList,pageIndex,pageSize );
			apiResultVo.setData( result );
			apiResultVo.setTotal( resultList.size() );
			apiResultVo.setCode( ReturnCode.SUCCESS );
			return apiResultVo;
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("行业分类-指数",e);
			apiResultVo.setCode(ReturnCode.ERROR);
			apiResultVo.setTradeId( LogTrace.getTrace().getTraceId() );
			return  apiResultVo;
		}

	}

	@ApiOperation(value = "行业分类-指数详情", notes = "行业分类-指数详情，x轴时间，y轴行业指数和涨幅")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "行业id", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "name", value = "行业名称", required = true, dataType = "String", paramType = "query")
	})
	@PostMapping("/getIndustryIndexDetail")
	public ApiResultVo<ApiIndustryIndexVo> getIndustryIndexDetail(@RequestParam(value = "id", required = true) Integer id,
																  @RequestParam(value = "name", required = true) String name){
		ApiResultVo apiResultVo = new ApiResultVo();
		try{
			apiResultVo = currencyService.getAllIndustryIndex(id,name);
			ApiIndustryIndexVo apiIndustryIndexVo = (ApiIndustryIndexVo) apiResultVo.getData();

			if(apiIndustryIndexVo!=null){
				apiResultVo.setData( apiIndustryIndexVo );
				apiResultVo.setCode( ReturnCode.SUCCESS );
			}else{
				apiResultVo.setCode( ReturnCode.DATA_NOT_EXIST );
			}

			return apiResultVo;
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("行业分类-指数详情",e);
			apiResultVo.setCode(ReturnCode.ERROR);
			apiResultVo.setTradeId( LogTrace.getTrace().getTraceId() );
			return  apiResultVo;
		}

	}

	/**
	 * 概念行情
	 */
	@ApiOperation(value = "概念行情" , notes = "概念行情")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageIndex", value = "页数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "条数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "field", value = "排序字段", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "排序方式（desc:降序，asc:升序）", required = true, dataType = "String", paramType = "query"),
	})
	@PostMapping("conceptIndex")
	public ApiResultVo<List<ConceptQuotationVo>> conceptIndex(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,
															  @RequestParam(value = "pageSize", required = true) Integer pageSize,
															  @RequestParam(value = "field", required = true) String field,
															  @RequestParam(value = "type", required = true) String type
	){
		CurrencyQuotationVo currencyQuotationVo = new CurrencyQuotationVo();
		currencyQuotationVo.setPageIndex( pageIndex );
		currencyQuotationVo.setPageSize( pageSize );
		currencyQuotationVo.setField( field );
		currencyQuotationVo.setType( type );
		ApiResultVo api=currencyService.conceptIndex(currencyQuotationVo);
		return api;
	}


	/**
	 * 概念行情
	 */
	@ApiOperation(value = "概念指数详情" , notes = "概念指数详情")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "conceptId", value = "概念id", required = true, dataType = "Integer", paramType = "query")
	})
	@PostMapping("conceptIndexById")
	public ApiResultVo<List<ConceptQuotationVo>> conceptIndexById(@RequestParam(value = "conceptId", required = true) Integer conceptId
	){
		ApiResultVo api=currencyService.conceptIndexById( conceptId );
		return api;
	}

	/**
	 * 概念货币列表
	 */
	@ApiOperation(value = "概念货币列表" , notes = "概念货币列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "conceptId", value = "概念id", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "pageIndex", value = "页数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "条数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "field", value = "排序字段", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "排序方式（desc:降序，asc:升序）", required = true, dataType = "String", paramType = "query")
	})
	@PostMapping("CurrencysByConceptId")
	public ApiResultVo<List<CurrencyQuotationResultVo>> CurrencysByConceptId(@RequestParam(value = "conceptId", required = true) Integer conceptId,
																	  @RequestParam(value = "pageIndex", required = true) Integer pageIndex,
																	  @RequestParam(value = "pageSize", required = true) Integer pageSize,
																	  @RequestParam(value = "field", required = true) String field,
																	  @RequestParam(value = "type", required = true) String type
	){
		ApiResultVo api=currencyService.CurrencysByConceptId( conceptId ,pageIndex,pageSize,field.trim() ,type.trim());
		return api;
	}


	/**
	 * 概念货币列表
	 */
	@ApiOperation(value = "行业货币列表" , notes = "行业货币列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "industryId", value = "行业id", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "pageIndex", value = "页数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "条数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "field", value = "排序字段", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "排序方式（desc:降序，asc:升序）", required = true, dataType = "String", paramType = "query")
	})
	@PostMapping("CurrencysByIndustryId")
	public ApiResultVo<List<CurrencyQuotationResultVo>> CurrencysByIndustryId(@RequestParam(value = "industryId", required = true) Integer industryId,
																			 @RequestParam(value = "pageIndex", required = true) Integer pageIndex,
																			 @RequestParam(value = "pageSize", required = true) Integer pageSize,
																			 @RequestParam(value = "field", required = true) String field,
																			 @RequestParam(value = "type", required = true) String type
	){
		ApiResultVo api=currencyService.CurrencysByIndustryId( industryId ,pageIndex,pageSize,field.trim() ,type.trim());
		return api;
	}


	/**
	 * 市值榜
	 */
	@ApiOperation(value = "市值榜" , notes = "市值榜")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageIndex", value = "页数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "条数", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "field", value = "排序字段", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "排序方式（desc:降序，asc:升序）", required = true, dataType = "String", paramType = "query")
	})
	@PostMapping("marketCapCny")
	public ApiResultVo<List<CurrencyQuotationResultVo>> marketCapCny(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,
																 @RequestParam(value = "pageSize", required = true) Integer pageSize,
																	 @RequestParam(value = "field", required = true) String field,
																	 @RequestParam(value = "type", required = true) String type
	){
		CurrencyQuotationVo currencyQuotationVo = new CurrencyQuotationVo();
		currencyQuotationVo.setField( field );
		currencyQuotationVo.setType( type );
		currencyQuotationVo.setPageIndex( pageIndex );
		currencyQuotationVo.setPageSize( pageSize );
		ApiResultVo apiResultVo=currencyService.getCurrencyQuotation( currencyQuotationVo );
		List<CurrencyQuotationResultVo> currencyQuotationResultVoList = (List<CurrencyQuotationResultVo>) apiResultVo.getData();
        //分页
		if(currencyQuotationVo.getPageIndex()==null){
			currencyQuotationVo.setPageIndex( 1 );
		}
		if(currencyQuotationVo.getPageSize()==null){
			currencyQuotationVo.setPageSize( 15 );
		}
		Object result= StringUtil.pageBean(currencyQuotationResultVoList,currencyQuotationVo.getPageIndex(),currencyQuotationVo.getPageSize()  );
		apiResultVo.setData( result );
		apiResultVo.setTotal( currencyQuotationResultVoList.size() );

		return apiResultVo;
	}

	/**
	 * 主流货币
	 */
	@ApiOperation(value = "主流货币" , notes = "主流货币")
	@PostMapping("mainCurrency")
	public ApiResultVo<List<CurrencyQuotationResultVo>> mainCurrency(){
		ApiResultVo apiResultVo=new ApiResultVo();
		try {
			List<String> list = new ArrayList<>(  );
			List<CurrencyQuotationResultVo> currencyQuotationResultVolist = new ArrayList<>(  );
			list.add( "bitcoin" );
			list.add( "ethereum" );
			list.add( "eos" );
			for(int i=0;i<list.size();i++){
				CurrencyQuotationResultVo currencyQuotationResultVo = currencyService.getCurrencyByCmcId( list.get( i ) );
				if(currencyQuotationResultVo!=null && currencyQuotationResultVo.getId()!=null){
					ExchangeTransactionpairMiddle exchangeTransactionpairMiddle = new ExchangeTransactionpairMiddle();
					exchangeTransactionpairMiddle.setCurrencyId( Integer.valueOf( currencyQuotationResultVo.getId()) );
					List<ExchangeTransactionpairMiddle>	ExchangeTransactionpairMiddleList=exchangeTransactionpairMiddleMapper.selectByEntityList( exchangeTransactionpairMiddle );
					if(currencyQuotationResultVo!=null){
						if(ExchangeTransactionpairMiddleList.size()>0){
							String priceRedisKey = RedisKeyApp.COIN_PRICE+list.get( i );
							String priceRedisData = redisServer.get(priceRedisKey);
							if(StringUtils.isNotBlank(priceRedisData)){
								CoinPriceVo coinPriceVoOld = JSON.parseObject(priceRedisData,CoinPriceVo.class);
								String cny = coinPriceVoOld.getPriceCny();
								if(StringUtils.isNotBlank( cny )){
									currencyQuotationResultVo.setPriceCny( Double.parseDouble( cny ) );
								}
								currencyQuotationResultVo.setLastOpenPrice( coinPriceVoOld.getPriceUsd() );
								if(coinPriceVoOld.getChang24h()!=null){
									currencyQuotationResultVo.setChange24h( Double.parseDouble( coinPriceVoOld.getChang24h() ) );
								}
							}
						}
					}
				}
				currencyQuotationResultVolist.add( currencyQuotationResultVo );
			}
			apiResultVo.setCode( ReturnCode.SUCCESS);
			apiResultVo.setData( currencyQuotationResultVolist );
			apiResultVo.setTradeId( LogTrace.getTrace().getTraceId() );
			apiResultVo.setTotal( currencyQuotationResultVolist.size() );
		}catch (Exception e){
			apiResultVo.setCode(ReturnCode.ERROR);
			apiResultVo.setTradeId( LogTrace.getTrace().getTraceId() );
		}
		return apiResultVo;
	}

	/**
	 * 货币详情
	 */
	@ApiOperation(value = "货币详情" , notes = "货币详情")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "cmcId", value = "cmcId", required = true, dataType = "Integer", paramType = "query")
	})
	@PostMapping("currencyDetail")
	public ApiResultVo<List<CurrencyQuotationResultVo>> currencyDetail(@RequestParam(value = "cmcId", required = true) String cmcId,HttpServletRequest request){
		ApiResultVo apiResultVo=new ApiResultVo();
		apiResultVo.setTradeId( LogTrace.getTrace().getTraceId() );
		try {
			CurrencyQuotationResultVo currencyQuotationResultVo = currencyService.getCurrencyByCmcId( cmcId );

				if(currencyQuotationResultVo!=null){
					if(currencyQuotationResultVo.getId()!=null){
						ExchangeTransactionpairMiddle exchangeTransactionpairMiddle = new ExchangeTransactionpairMiddle();
						exchangeTransactionpairMiddle.setCurrencyId( Integer.valueOf( currencyQuotationResultVo.getId() ));
						List<ExchangeTransactionpairMiddle> ExchangeTransactionpairMiddleList=exchangeTransactionpairMiddleMapper.selectByEntityList( exchangeTransactionpairMiddle );
						if(ExchangeTransactionpairMiddleList.size()>0){
							String priceRedisKey = RedisKeyApp.COIN_PRICE+cmcId;
							String priceRedisData = redisServer.get(priceRedisKey);
							if(StringUtils.isNotBlank(priceRedisData)){
								CoinPriceVo coinPriceVoOld = JSON.parseObject(priceRedisData,CoinPriceVo.class);
								String cny = coinPriceVoOld.getPriceCny();
								if(StringUtils.isNotBlank( cny )){
									currencyQuotationResultVo.setPriceCny( Double.parseDouble( cny ) );
								}
								currencyQuotationResultVo.setLastOpenPrice( coinPriceVoOld.getPriceUsd() );
								if(coinPriceVoOld.getChang24h()!=null){
									currencyQuotationResultVo.setChange24h( Double.parseDouble( coinPriceVoOld.getChang24h() ) );
								}
								if(StringUtils.isNotBlank( coinPriceVoOld.getPriceCny24H())){
									currencyQuotationResultVo.setDifference( Double.parseDouble( coinPriceVoOld.getPriceCny24H()) );
								}
							}
						}
					}

					//判断用户是否已经自选
					String token = RequestUtil.getHeaderName(request  , HttpHeaderCons.TOKEN);
					BtUser btUser = commonService.getUserByToken(token);
					if(btUser!=null){
						Integer	user_id = btUser.getId();
						List<Integer> middleList = new ArrayList<>();
						middleList.add(Integer.valueOf(currencyQuotationResultVo.getId()));

						if(middleList.size() > 0){
							Map<String,Object> params = new HashMap<>();
							params.put("type",2);
							params.put("uniqueAnnotationList",middleList);
							params.put("user_id",user_id);
							List<SelfSelected> selfList = selfSelectedMapper.getSelfSelectByMideleId(params);
							if(selfList != null && selfList.size()>0){
								Map<Integer,Object> selfMap = new HashMap<>();
								for(SelfSelected selfSelected : selfList){
									selfMap.put(selfSelected.getUniqueAnnotation(),selfSelected.getUniqueAnnotation());
								}
								if(Integer.valueOf(currencyQuotationResultVo.getId()) != null && selfMap.containsKey(Integer.valueOf(currencyQuotationResultVo.getId()))){
									currencyQuotationResultVo.setSelfSelectFlag(1);
								}else{
									currencyQuotationResultVo.setSelfSelectFlag(2);
								}
							}
						}
					}
					apiResultVo.setCode( ReturnCode.SUCCESS);
					apiResultVo.setData( currencyQuotationResultVo );
				}else{
					apiResultVo.setCode( ReturnCode.DATA_NOT_EXIST );
				}
		}catch (Exception e){
			apiResultVo.setCode(ReturnCode.ERROR);
			apiResultVo.setTradeId( LogTrace.getTrace().getTraceId() );
		}
		return apiResultVo;
	}


	@ApiOperation(value = "行情k线-市场行情", notes = "行情k线-市场行情")
	@PostMapping("/kActionQuantizationSearchMarket")
	public ApiResultVo<List<ApiKActionQuantizationVo>> kActionQuantizationSearchMarket(@RequestBody kActionQuantizationParamsVo kActionQuantizationParamsVo){
		return currencyService.kActionQuantizationSearchMarket(kActionQuantizationParamsVo);
	}

	@ApiOperation(value = "货币简况", notes = "货币简况")
	@GetMapping("/getProjectOverview")
	public ApiResultVo<ProjectOverviewVo> getProjectOverview(@RequestParam(value = "cmcId") String cmcId){
		return currencyService.getProjectOverviewByCmcId(cmcId);
	}

	/**
	 * 市场表现
	 */
	@ApiOperation(value = "市场表现" , notes = "市场表现(参数cmcId,x轴是时间，y轴:价格，y1:大盘综合指数变化率，y2是行业指数变化率)")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "cmcId", value = "货币cmcId", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "查询类型（3：3小时数据;24：1天数据）", required = true, dataType = "String", paramType = "query")
	})
	@PostMapping("MarketPer")
	public ApiResultVo<List<MarketPerVo>> MarketPer(@RequestParam(value = "cmcId", required = true) String cmcId,
	@RequestParam(value = "type", required = true) Integer type
	){
		LogTrace.info("市场表现", "开始执行MarketPer市场表现接口，参数cmcId:",cmcId);
		Long jStart = System.currentTimeMillis();
		ApiResultVo api=currencyService.MarketPer(cmcId,type);
		LogTrace.info("市场表现查询","总耗时",String.valueOf(System.currentTimeMillis()-jStart));
		return api;
	}

	/**
	 * 压力支撑
	 */
	@ApiOperation(value = "压力支撑" , notes = "压力支撑(参数cmcId，x轴：时间，y轴：价格，y1：行情压力位，y2：行情支撑位)")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "cmcId", value = "货币cmcId", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "查询类型（3：3小时数据;24：1天数据）", required = true, dataType = "String", paramType = "query")
	})
	@PostMapping("PressureSup")
	public ApiResultVo<List<PressureSupVo>> PressureSup(@RequestParam(value = "cmcId", required = true) String cmcId,
														@RequestParam(value = "type", required = true) Integer type){
		LogTrace.info("压力支撑", "开始执行PressureSup压力支撑接口，参数cmcId:",cmcId);
		Long jStart = System.currentTimeMillis();
		ApiResultVo api=currencyService.PressureSup(cmcId,type);
		LogTrace.info("压力支撑查询","总耗时",String.valueOf(System.currentTimeMillis()-jStart));
		return api;
	}

	/**
	 * 平均成本
	 */
	@ApiOperation(value = "平均成本" , notes = "平均成本(参数cmcId，x轴：时间，y轴：现时价格，y1轴：平均成本)")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "cmcId", value = "货币cmcId", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "查询类型（3：3小时数据;24：1天数据）", required = true, dataType = "String", paramType = "query")
	})
	@PostMapping("avgCost")
	public ApiResultVo<List<AvgCostVo>> avgCost(@RequestParam(value = "cmcId", required = true) String cmcId,
												@RequestParam(value = "type", required = true) Integer type) {
		LogTrace.info("平均成本", "开始执行avgCost平均成本接口，参数cmcId:",cmcId);
		Long jStart = System.currentTimeMillis();
		ApiResultVo api=currencyService.avgCost(cmcId,type);
		LogTrace.info("平均成本查询","总耗时",String.valueOf(System.currentTimeMillis()-jStart));
		return api;
	}

	/**
	 * 多空趋势
	 */
	@ApiOperation(value = "多空趋势" , notes = "多空趋势(参数cmcId，x轴：时间，y轴：现时价，y1：过去24小时平均价，y2:过去5小时平均价)")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "cmcId", value = "货币cmcId", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "查询类型（3：3小时数据;24：1天数据）", required = true, dataType = "String", paramType = "query")
	})
	@PostMapping("spaceTrend")
	public ApiResultVo<List<SpaceTrendVo>> spaceTrend(@RequestParam(value = "cmcId", required = true) String cmcId,
													  @RequestParam(value = "type", required = true) Integer type){
		LogTrace.info("多空趋势", "开始执行spaceTrend多空趋势接口，参数cmcId:",cmcId);
		Long jStart = System.currentTimeMillis();
		ApiResultVo api=currencyService.spaceTrend(cmcId,type);
		LogTrace.info("多空趋势查询","总耗时",String.valueOf(System.currentTimeMillis()-jStart));
		return api;
	}

	/**
	 * 平台币概念指数
	 */
	@ApiOperation(value = "平台币概念指数" , notes = " 平台币概念指数(参数：id(概念id))")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "hour", value = "hour:3：3小时;24：1日;", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "day", value = "day", required = true, dataType = "String", paramType = "query")
	})
	@PostMapping("bottomteZhi")
	public ApiResultVo<List<GaiNianZhiShuVo>> bottomteZhi(@RequestParam(value = "id", required = true) Integer id,
														  @RequestParam(value = "hour", required = true) Integer hour,
														  @RequestParam(value = "day", required = true) Integer day
	){
		LogTrace.info("平台币概念指数","开始执行bottomteZhi平台币概念指数接口，参数概念id:",id+"");
		Long jStart = System.currentTimeMillis();
		ApiResultVo api=currencyService.bottomteZhi(id,hour,day);
		LogTrace.info("平台币概念指数查询","总耗时",String.valueOf(System.currentTimeMillis()-jStart));
		return api;
	}

	/**
	 * 行业指数
	 */
	@ApiOperation(value = "行业指数" , notes = " 行业指数(参数：id(行业id))")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "hour", value = "hour:3：3小时;24：1日;", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "day", value = "day", required = true, dataType = "String", paramType = "query")
	})
	@PostMapping("industryIndex")
	public ApiResultVo<List<GaiNianZhiShuVo>> industryIndex(@RequestParam(value = "id", required = true) Integer id,
														  @RequestParam(value = "hour", required = true) Integer hour,
														  @RequestParam(value = "day", required = true) Integer day
	){
		LogTrace.info("行业指数","开始执行industry行业指数接口，参数行业id:",id+"");
		Long jStart = System.currentTimeMillis();
		ApiResultVo api=currencyService.industryIndex(id,hour,day);
		LogTrace.info("行业指数","总耗时",String.valueOf(System.currentTimeMillis()-jStart));
		return api;
	}


	/**
	 * 货币价格趋势图
	 */
	@ApiOperation(value = "货币价格趋势图" , notes = " 货币价格趋势图(参数：cmcId(货币cmcId))")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "cmcId", value = "cmcId", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "hour", value = "hour:3：3小时;24：1日;", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "day", value = "day", required = true, dataType = "String", paramType = "query")
	})
	@PostMapping("currencyIndex")
	public ApiResultVo<List<GaiNianZhiShuVo>> currencyIndex(@RequestParam(value = "cmcId", required = true) String cmcId,
															@RequestParam(value = "hour", required = true) Integer hour,
															@RequestParam(value = "day", required = true) Integer day
	){
		LogTrace.info("货币价格趋势图","开始执行currencyIndex货币价格趋势图接口，参数货币cmcId:",cmcId+"");
		Long jStart = System.currentTimeMillis();
		ApiResultVo api=currencyService.currencyIndex(cmcId,hour,day);
		LogTrace.info("货币价格趋势图","总耗时",String.valueOf(System.currentTimeMillis()-jStart));
		return api;
	}


	@ApiOperation(value = "资金流入今日3小时、24小时", notes = "资金流入今日3小时、24小时")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "cmcId", value = "货币cmcId", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "timePart", value = "3h/1d", required = true, dataType = "String", paramType = "query")
	})
	@GetMapping("/capitalInflowSituation")
	public ApiResultVo<ChartVo> capitalInflowSituation(@RequestParam(value = "cmcId") String cmcId, @RequestParam(value = "timePart") String timePart) {
		ApiResultVo api=new ApiResultVo();
		try {
			api= currencyService.capitalInflowSituation( cmcId, timePart );
		} catch (HbaseCloseExcetion hbaseCloseExcetion) {
			hbaseCloseExcetion.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (HbaseGetTableExcetion hbaseGetTableExcetion) {
			hbaseGetTableExcetion.printStackTrace();
		} catch (HbaseConnectionExcetion hbaseConnectionExcetion) {
			hbaseConnectionExcetion.printStackTrace();
		}

		return api;
	}

	/**
	 * 资金流入5日柱状图
	 */
	@ApiOperation(value = "资金流入5日柱状图" , notes = " 资金流入5日柱状图")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "cmcId", value = "cmcId", required = true, dataType = "String", paramType = "query"),
	})
	@PostMapping("capitalInflowSituationHistogram")
	public ApiResultVo<List<ChartVo>> capitalInflowSituationHistogram(@RequestParam(value = "cmcId", required = true) String cmcId
	){
		LogTrace.info("资金流入5日柱状图","开始执行资金流入5日柱状图接口，参数货币cmcId:",cmcId+"");
		Long jStart = System.currentTimeMillis();
		ApiResultVo api=new ApiResultVo();
		try {
			 api=currencyService.capitalInflowSituationHistogram(cmcId);
		} catch (HbaseCloseExcetion hbaseCloseExcetion) {
			hbaseCloseExcetion.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (HbaseGetTableExcetion hbaseGetTableExcetion) {
			hbaseGetTableExcetion.printStackTrace();
		} catch (HbaseConnectionExcetion hbaseConnectionExcetion) {
			hbaseConnectionExcetion.printStackTrace();
		}
		LogTrace.info("资金流入5日柱状图","总耗时",String.valueOf(System.currentTimeMillis()-jStart));
		return api;
	}

	/**
	 * 24H资金流向分布
	 */
	@ApiOperation(value = "24H资金流向分布" , notes = "24H资金流向分布")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "cmcId", value = "cmcId", required = true, dataType = "String", paramType = "query"),
	})
	@PostMapping("capitalFlowDistribution24H")
	public ApiResultVo<TradesHistoryData>  capitalFlowDistribution24H(@RequestParam(value = "cmcId", required = true) String cmcId
	){
		LogTrace.info("24H资金流向分布","开始执行24H资金流向分布接口，参数货币cmcId:",cmcId+"");
		Long jStart = System.currentTimeMillis();
		ApiResultVo api=new ApiResultVo();
		try {
			api=currencyService.capitalFlowDistribution24H(cmcId);
		} catch (HbaseCloseExcetion hbaseCloseExcetion) {
			hbaseCloseExcetion.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (HbaseGetTableExcetion hbaseGetTableExcetion) {
			hbaseGetTableExcetion.printStackTrace();
		} catch (HbaseConnectionExcetion hbaseConnectionExcetion) {
			hbaseConnectionExcetion.printStackTrace();
		}
		LogTrace.info("24H资金流向分布","总耗时",String.valueOf(System.currentTimeMillis()-jStart));
		return api;
	}



	/**
	 * 货币价格趋势图
	 */
	@ApiOperation(value = "货币分析统计" , notes = "货币分析统计")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "cmcId", value = "cmcId", required = true, dataType = "String", paramType = "query"),
	})
	@PostMapping("capitalStatistics")
	public ApiResultVo<CurrencyStatistics>  capitalStatistics(@RequestParam(value = "cmcId", required = true) String cmcId
	){
		LogTrace.info("货币分析统计","开始执行货币分析统计接口，参数货币cmcId:",cmcId+"");
		Long jStart = System.currentTimeMillis();
		ApiResultVo api=new ApiResultVo();
		api.setTradeId( LogTrace.getTrace().getTraceId() );

		try{
			CurrencyQuotationResultVo currencyQuotationResultVo = currencyService.getCurrencyByCmcId( cmcId );

			if(currencyQuotationResultVo!=null){
				CurrencyStatistics currencyStatistics = new CurrencyStatistics();
				currencyStatistics.setTurnover( String.valueOf( StringUtil.getDoubleTwo( currencyQuotationResultVo.getTurnover() ) ) );
				currencyStatistics.setVolume24h( String.valueOf( new BigDecimal(currencyQuotationResultVo.getVolume24h() )) );

				//24小时涨幅
				CoinPriceVo coinPriceVo = currencyService.getNewPrice( currencyQuotationResultVo.getCmcId() );
				if(coinPriceVo!=null){
					currencyStatistics.setChange24h( coinPriceVo.getChang24h() );
				}
				String netInflow = redisServer.get( RedisKeyApp.FLOW_INDEX+currencyQuotationResultVo.getCmcId() );
				if(StringUtils.isNotBlank( netInflow )){
					currencyStatistics.setNetInflow( String.valueOf(new BigDecimal( netInflow) ) );
				}

				//1小时涨幅
				Long nowTImeres = DateUtils.getCurrentDataLong();
				LocalDateTime timeres = DateUtils.getDateTimeOfTimestamp( nowTImeres );
				String redisPriceDate = DateUtils.localDateTimeFormatString(timeres,DateUtils.format_ymds);
				CurrencyInfo info = redisCacheComponent.getCurrencyInfo(cmcId);
				ExchangeTransactionpairMiddle exchangeTransactionpairMiddle = new ExchangeTransactionpairMiddle();
				exchangeTransactionpairMiddle.setCurrencyId( info.getId() );
				List<ExchangeTransactionpairMiddle>  ExchangeTransactionpairMiddleList=exchangeTransactionpairMiddleMapper.selectByEntityList( exchangeTransactionpairMiddle );

				double change1h = 0;
				for(int i=0;i<ExchangeTransactionpairMiddleList.size();i++){
					exchangeTransactionpairMiddle = ExchangeTransactionpairMiddleList.get( i );
					int exchangeId = exchangeTransactionpairMiddle.getExchangeId();
					String transactionName = exchangeTransactionpairMiddle.getTransactionName();
					String Rediskey = RedisKeysUtils.API_SERVICE_K_ACTION_ALL_DATA_PRICE + "@" + exchangeId + "@" + transactionName;
					String API_SERVICE_K_ACTION_CHANGE_PRICE = redisServer.get( Rediskey );
					if(StringUtils.isNotBlank( API_SERVICE_K_ACTION_CHANGE_PRICE )){
						KActionTotalPo rActionTotalPo = JSON.parseObject( API_SERVICE_K_ACTION_CHANGE_PRICE,KActionTotalPo.class );
						if(StringUtils.isNotBlank( rActionTotalPo.getChangePrice1H() )){
							change1h=Double.parseDouble( rActionTotalPo.getChangePrice1H() )+change1h;
						}
					}
				}
				if(ExchangeTransactionpairMiddleList.size()>0){
					currencyStatistics.setChange1h( String.valueOf( StringUtil.getDoubleTwo( change1h/ExchangeTransactionpairMiddleList.size()) ) );
				}

				//7小时涨幅
				String change7Day = redisServer.get( RedisKeyApp.INCREASE7DAY_INDEX+cmcId );
				if(StringUtils.isNotBlank( change7Day )){
					currencyStatistics.setChange7Day( change7Day );
				}
				api.setData( currencyStatistics );
				api.setCode( ReturnCode.SUCCESS );
			}else{
				api.setCode( ReturnCode.DATA_NOT_EXIST );
			}
		}catch (Exception e){
			e.printStackTrace();
			LogTrace.error("货币分析统计",e);
			api.setCode(ReturnCode.ERROR);
		}
		LogTrace.info("货币分析统计","总耗时",String.valueOf(System.currentTimeMillis()-jStart));
		return api;
	}

}
